# -*- coding: utf-8 -*-

import re
import json
from decimal import Decimal
import datetime
import urllib.request

P_SAFE_COMMAND = re.compile("([`!&()|;'\"<>])")


def safe_command(src_string):
    """主要用于linux，文件路径，解压密码中可能存在特殊字符，需要转义"""
    return P_SAFE_COMMAND.sub(r'\\\1', src_string)


class JsonEncoderPatch(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, Decimal):
            return "%s" % obj
        if isinstance(obj, datetime.datetime):  # datetime 会被判定为 date, date 不会被判定为 datetime   所以顺序不能错 
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        if isinstance(obj, datetime.date):
            return obj.strftime('%Y-%m-%d')
        return json.JSONEncoder.default(self, obj)


def json_dumps(obj, **kwargs):
    if 'separators' not in kwargs:
        kwargs['separators'] = (',', ':')
    if 'cls' not in kwargs:
        kwargs['cls'] = JsonEncoderPatch
    return json.dumps(obj, **kwargs)


def json_dump(obj, fp, **kwargs):
    if 'separators' not in kwargs:
        kwargs['separators'] = (',', ':')
    if 'cls' not in kwargs:
        kwargs['cls'] = JsonEncoderPatch
    return json.dump(obj, fp, **kwargs)


def get_response_headers(url):
    """requests获取headers有bug，有的地址获取不到Content-Length"""
    opener = urllib.request.build_opener()
    request = urllib.request.Request(url)
    response = opener.open(request)
    return dict(response.headers)
